package com.lsf.studentmanagerup.servlet;

import com.lsf.studentmanagerup.bean.PageBean;
import com.lsf.studentmanagerup.bean.Student;
import com.lsf.studentmanagerup.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 李树飞
 */
@WebServlet(name = "GetUserByPageServlet",urlPatterns = "/getUserByPage")
public class GetUserByPageServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        //获取请求中的当前页码和每页显示条数的参数
        String currentPage = request.getParameter("currentPage");
        String rows = request.getParameter("rows");
        //检查是否为空，为空则设置默认值
        if (currentPage == null || "".equals(currentPage)) {
            currentPage = "1";
        }
        if (rows == null || "".equals(rows)) {
            rows = "5";
        }

        //获取条件查询参数并以Map形式保存
        Map<String, String> condition = new HashMap<>();
        condition.put("id", request.getParameter("id"));
        condition.put("name", request.getParameter("name"));
        condition.put("gender", request.getParameter("gender"));
        condition.put("birthday", request.getParameter("birthday"));
        condition.put("email", request.getParameter("email"));
        condition.put("comment", request.getParameter("comment"));
        //调用服务层的根据条件分页查询包含对应学生信息的分页对象的服务
        StudentService studentService = new StudentService();
        PageBean<Student> pageBean = studentService.getStudentsByPageService(currentPage, rows, condition);

        //将分页对象存入request中
        request.setAttribute("pb", pageBean);
        request.setAttribute("condition", condition);
        //转发到main.jsp
        request.getRequestDispatcher("main.jsp").forward(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
